package leecode;

import java.util.Stack;

/**
 * @author huanggy
 * @date 2023/02/13
 **/
public class Solution {


    public static void main(String[] args) {
        ListNode l1 = new ListNode();
        ListNode l11 = new ListNode();
        ListNode l111 = new ListNode();
        l1.val = 2;
        l11.val = 4;
//        l111.val = 3;
        l1.next = l11;
//        l11.next = l111;


        ListNode l2 = new ListNode();
        ListNode l21 = new ListNode();
        ListNode l211 = new ListNode();
        l2.val = 5;
        l21.val = 6;
        l211.val = 4;
        l2.next = l21;
        l21.next = l211;
        new Solution().addTwoNumbers(l1, l2);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        // 入栈
        Stack<Integer> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();

        while (l1.next != null) {
            s1.push(l1.val);
            l1 = l1.next;
        }
        s1.push(l1.val);

        while (l2.next != null) {
            s2.push(l2.val);
            l2 = l2.next;
        }
        s2.push(l2.val);

        // 计算
        ListNode result = new ListNode();
        ListNode current = result;
        int length = s1.size() > s2.size() ? s1.size() : s2.size();
        int lastResult = 0;
        for (int i = 0; i < length; i++) {
            int i1 = s1.empty() ? 0 : s1.pop();
            int i2 = s2.empty() ? 0 : s2.pop();
            int sumTmp = i1 + i2 + lastResult;
            if (sumTmp >= 10) {
                lastResult = 1;
                sumTmp = sumTmp - 10;
            }
            current.val = sumTmp;
            if (i < length - 1) {
                ListNode next = new ListNode();
                current.next = next;
                current = next;
            }
        }
        return result;
    }


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
